package cl.usm.taller.corona.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.opensymphony.xwork2.conversion.TypeConversionException;

public class StringToDateTimeConverter extends StrutsTypeConverter {

    private static final DateFormat DATETIME_FORMAT = new SimpleDateFormat("dd-MM-yyyy");

	@Override
	public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
		int a=1;
		a++;
		
		if (arg1 == null || arg1.length == 0 || arg1[0].trim().length() == 0) {
            return null;
        }

        try {
            return DATETIME_FORMAT.parse(arg1[0]);
        } catch (ParseException e) {
            throw new TypeConversionException("Unable to convert given object to date: " + arg1[0]);
        }

	}

	@Override
	public String convertToString(Map arg0, Object date) {
		// TODO Auto-generated method stub
		if (date != null && date instanceof Date) {         
            return DATETIME_FORMAT.format(date);
        } else {
            return null;
        }
	}

}
